package com.example.toutiao.view

import android.content.Context
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import com.example.toutiao.R

/**
 * 复写 输入框
 */
class CodeEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = R.attr.editTextStyle
) : AppCompatEditText(context, attrs, defStyleAttr) {
    private var draw: Drawable? = null
    private var drawShow: Drawable? = null


    /**
     * 初始化 获取本地资源 图标
     * 这里自行设置的原因是 图片资源的200x200 导致 过大，而又不能直接设置
     * 通过属性设置minimumWidth  minimumHeight 于是就再此设置啦
     */
    init {
        addTextChangedListener(TextWatcherEditText())
    }

    /**
     * 监听触摸时间
     */
    private inner class TextWatcherEditText : TextWatcher {
        /**
         * 下面的方法是复写 TextWatcher的三个方法
         */
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(
            text: CharSequence?,
            start: Int,
            lengthBefore: Int,
            lengthAfter: Int
        ) {
            var textContent = text.toString()
            val length: Int = textContent.length
            if (length == 2 || length == 4||length==6) {
                textContent = if (textContent.substring(length - 1) == " ") {
                    textContent.substring(0, length - 1)
                } else {
                    textContent.substring(0, length - 1) + " " + textContent.substring(length - 1)
                }
                setText(textContent)
                setSelection(textContent.length)
            }
//            onTextChanged(text, start, lengthBefore, lengthAfter)
        }

        /**
         * 文本编辑框改变之后，
         * 判断是否需要显示后面的小图标
         * 该函数没有监听到 不知道是什么原因
         */
        override fun afterTextChanged(s: Editable?) {

        }
    }


}